import 'package:flutter/material.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:oramemo/common/utils/dialog_util.dart';
import 'package:oramemo/common/utils/extension_util.dart';
import 'package:oramemo/core/config/api_config.dart';
import 'package:oramemo/core/controllers/auth_controller.dart';
import 'package:oramemo/core/controllers/profile_controller.dart';
import 'package:path/path.dart';
import 'dart:io';
import 'avatar_service.dart';
import 'avatar_picker_dialog.dart';
import 'package:oramemo/common/langs/text_key.dart';

class AvatarUploadHelper {
  final AvatarService _avatarService = AvatarService();
  final ProfileController _apiService = Get.find();
  final logic = Get.find<AuthController>();
  final BuildContext context; // 添加context参数

  AvatarUploadHelper(this.context); // 构造函数接收context

  Future<void> showPickerDialog() async {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return AvatarPickerDialog(
          onCameraTap: _takePhoto,
          onGalleryTap: _pickFromGallery,
        );
      },
    );
  }

  Future<void> _takePhoto() async {
    try {
      final File? image = await _avatarService.takePhoto();
      if (image != null) {
        await _uploadAvatar(image); // 传入image参数
      }
    } catch (e) {
      TipUtil.showError(TextKey.avatarUploadError.tr);
    }
  }

  Future<void> _pickFromGallery() async {
    try {
      final File? image = await _avatarService.pickFromGallery();
      if (image != null) {
        await _uploadAvatar(image); // 传入image参数
      }
    } catch (e) {
      TipUtil.showError(TextKey.avatarUploadError.tr);
    }
  }

  Future<void> _uploadAvatar(File img) async {
    final response = await _apiService.uploadAvatar(img);
    if (response?.isSuccess == true) {
      await logic.getUserInfo(); // 等待用户信息更新完成
    }
  }
}
